package com.kaibes.admin.user;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import com.kaibes.core.base.util.StringUtils;
import com.kaibes.module.user.UserService;
import com.kaibes.module.user.pojo.User;
import com.kaibes.web.filter.BasicInterceptor;

@Component
public class UserHandlerInterceptor implements BasicInterceptor {

    @Autowired
    private UserService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        if (handler instanceof ResourceHttpRequestHandler) {
            return true;
        }
        User user = (User) request.getSession(true).getAttribute("user");
        Integer userId = (Integer) request.getAttribute("userId");
        if (checkUser(user, userId)) {
            if (userId != null) {
                user = userService.getById(userId);
            }
            if (checkUser(user, userId)) {
                user = new User();
                user.setName("游客");
                user.setNickname("游客");
            }
            request.getSession(true).setAttribute("user", user);
        }
        request.setAttribute("user", user);
        return true;
    }
    
    private boolean checkUser(User user, Integer userId) {
        return user == null || user.getId() == null || !user.getId().equals(userId);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        if (response.getStatus() >= 200 && response.getStatus() < 300) {
            if (request.getRequestURI().startsWith("/users") && StringUtils.equals(request.getMethod(), "PUT", "POST")) {
                Integer userId = (Integer) request.getAttribute("userId");
                User user = userService.getById(userId);
                request.getSession(true).setAttribute("user", user);
            }
        }
    }
}
